package com.cyh.server.utils;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * @author chenyuehua
 * @description
 * @date 2025/5/28
 **/
@Component
public class DatasourceContextUtils {

    @Resource
    private DataSource dataSource;

    public boolean isDatasourceExist() {
        return DynamicDataSourceContextHolder.peek() != null;
    }

    public DataSource getPrimaryDatasource() {
        String peek = DynamicDataSourceContextHolder.peek();
        if (peek != null) {
            return dataSource;
        }
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        return ds.getDataSource(peek);
    }
}
